/**
 * jqGrid的扩展，依赖commons.js文件中对jquery的扩展方法$.wrap
 * @charset utf8
 * @autor liujhc
 */
(function($){
    var isGridOptions=function(o){//返回参数是否为jgGrid的配置
        return o && typeof o == 'object' && 'colModel' in o;
    }
    /**
     * jqGrid Bug补丁
     */
    $.fn.jqGrid=$.wrap($.fn.jqGrid,function(o){
        if(!isGridOptions(o)) return;
        //当reload时清除选择
        o.loadComplete=$.wrap(o.loadComplete,function(){
            this.p.selarrrow=[];
            this.p.selrow=null;
        });
    });
    /**
     * zebra 斑马线
     * 当使用树形表格treeGrid功能，斑马线功能将不被启用
     */
    $.fn.jqGrid=$.wrap($.fn.jqGrid,function(o){
        if(!isGridOptions(o) || o.zebra==false || o.treeGrid) return;
        var zebra=function($tr){
            $tr.addClass("list-odd").hover(function(){
                $(this).removeClass("list-odd");
            }, function(){
                if($(this).attr("aria-selected")!="true"){
                    $(this).addClass("list-odd");
                }
            });
        }
        var $table=this, rownum=0;
        o.afterInsertRow=$.wrap(o.afterInsertRow,function(){
            if((++rownum)%2==0){
                zebra($table.find("tr:eq("+rownum+")"));
            }
        });
        o.loadComplete=$.wrap(o.loadComplete,function(){
            $table.find("tr.jqgrow:odd").each(function(){
                zebra($(this));
            });
            rownum=0;
        });
    });

    /**
     * 自适应宽度
     */
    $.fn.jqGrid=$.wrap($.fn.jqGrid,function(o){
        if(!isGridOptions(o) || o.autowidth!==true) return;
        var treeResizing=false, $table=this;
        o.resizeStart=$.wrap(o.resizeStart,function(){//在调整列宽的时候不进行整个表格的宽度重置
            treeResizing=true;
        });
        o.resizeStop=$.wrap(o.resizeStop,function(){
            treeResizing=false;
        });
        var resizeTable=function(){//在窗口大小改变时，重置jqGrid的宽度
            if(!treeResizing){
                treeResizing = true;
                setTimeout(function(){
                    $(".ui-jqgrid-btable").each(function(){
                        $(this).setGridWidth($(this).parents(".ui-jqgrid").parent().width()-2);
                    });
                    //解决Chrome等浏览器中自适应宽度后仍出现滚动条的情况
                    //$table.parents(".ui-jqgrid-bdiv").width($table.width());
                    treeResizing=false;
                }, 100);
            }
        }
        o.loadComplete=$.wrap(o.loadComplete,resizeTable);
        $(window).resize(resizeTable);
        resizeTable();
    });
    
    /**
     * 活动列(调整列的显示与隐藏以及列之间的显示顺序)
    */
    $.fn.jqGrid=$.wrap($.fn.jqGrid,null,function(o){
        if(!isGridOptions(o) || !o.pager) return;
        $.extend($.jgrid.nav,{//禁止表格左下角的其他按钮的显示
            edit:false,
            add:false,
            del:false,
            search:false,
            refresh: false
        });
        var ts=$(this).get(0),
        tid=ts.p.id+'_';
        function remapColumns(th,colModel){
            var cmMap = {};
            $.each(colModel, function(i) {
                cmMap[this.name]=i;
            });
            var permutation = [];
            th.each(function(i) {
                var id = $(">div", this).get(0).id.replace(/^jqgh_/, "").replace(tid,"");
                if (id in cmMap) {
                    permutation.push(cmMap[id]);
                }
            });
            $(ts).jqGrid("remapColumns",permutation, true, true);
        }
        function encodeColModel(colModel){
            var result="",max=colModel.length-1;
            for(var i=0;;i++){
                result+=colModel[i].name+'/'+(colModel[i].hidden?0:1);
                if(i==max){
                    return result;
                }else{
                    result+='#';
                }
            }
        }
        function decodeColModel(str){
            if(!str) return null;
            var result=[],arr=(str||'').split('#'),max=arr.length-1;
            for(var i=0; ;i++){
                var a=arr[i].split('/');
                result.push({
                    name:a[0],
                    hidden:!parseInt(a[1])
                });
                if(i==max){
                    return result;
                }
            }
        }
        var colsId=tid+'cols',
        COOKIE_KEY=location.pathname+'#'+tid+'colModel',
        ulCss={
            listStyleType: 'none', 
            margin: 0, 
            padding: 5, 
            'float': 'left', 
            background: '#E5E5E5', 
            width: 143
        },
        liCss={
            margin: 5, 
            padding: 5, 
            fontSize: 12, 
            width: 120, 
            cursor:'pointer'
        };
        $('<div id="'+colsId+'"/>')
        .append('<ul class="visible"/>')
        .append('<ul class="hidden"/>')
        .insertAfter(this).hide().find("ul").css(ulCss);
        this.navGrid(o.pager).navButtonAdd(o.pager,{
            id:'colsActive',
            caption:'调整列',
            title:'调整显示列',
            buttonicon:'ui-icon-wrench',
            onClickButton:function(){
                var $hidden = $("#"+colsId+'>ul.hidden'),
                $visible = $("#"+colsId+'>ul.visible');
                $.each(ts.p.colModel,function(i){//生成li，供用户拖拽排序
                    $('<li/>').text(ts.p.colNames[i]).attr('sortable',this.sortable).attr('colName',this.name)[this.hidedlg?'hide':'show']()
                    .appendTo(this.hidden?$hidden:$visible).css(liCss)
                    .addClass(this.hidden?'ui-state-disabled':'ui-state-default');
                });
                $('#'+colsId).dialog({
                    title:'调整列',
                    width:330,
                    close:function(){
                        $hidden.empty();
                        $visible.empty();
                    }
                }).find('ul').sortable({
                    connectWith: "#"+colsId+">ul",
                    items: 'li:not([sortable=false])',
                    over: function(event, ui) {
                        $(ui.item).addClass('ui-state-highlight');
                    },
                    out: function(event, ui) {
                        $(ui.item).removeClass('ui-state-highlight');
                    },
                    update:function(event, ui){
                        var colName=$(ui.item).removeClass('ui-state-highlight').attr('colName'),
                        $th=$('#'+tid+colName);
                        if($(this).is('ul.visible')){
                            $(ui.item).addClass('ui-state-default').removeClass('ui-state-disabled');
                            $(ts).showCol(colName);
                            //更新排序
                            if($(ui.item).next().length==0){
                                $th.insertAfter('#'+tid+$(ui.item).prev().attr('colName'));
                            }else{
                                $th.insertBefore('#'+tid+$(ui.item).next().attr('colName'));
                            }
                            remapColumns($th.siblings().andSelf(),ts.p.colModel);
                        }else{
                            $(ui.item).addClass('ui-state-disabled').removeClass('ui-state-default');
                            $(ts).hideCol(colName);
                        }
                        setTimeout(function(){
                            var date=new Date();
                            date.setYear(date.getFullYear()+1);
                            $.cookies.set(COOKIE_KEY,encodeColModel(ts.p.colModel),{
                                expiresAt:date
                            });//将最新字段顺序和显示状态存入cookie
                            $(window).resize();
                        }, 100);
                    }
                }).disableSelection();
            }
        });
        //如果cookie中有排序的列名，恢复用户的设置
        var colModel=decodeColModel($.cookies.get(COOKIE_KEY));
        if($.isArray(colModel)&&colModel.length>0){
            var cmMap = {},$parent=$('#'+tid+colModel[0].name).parent();
            $.each(colModel, function(i){
                cmMap[this.name]=i;
                var hidden=this.hidden;
                var $th=$('#'+tid+this.name);
                if(hidden===true){
                    $(ts).hideCol(this.name);
                }else{
                    $(ts).showCol(this.name);
                }
                setTimeout(function(){
                    $th[hidden===true?'hide':'show']();
                }, 100);
                if(i!=0){
                    $th.insertAfter('#'+tid+colModel[i-1].name);
                }
            });
            remapColumns($('>th',$parent), ts.p.colModel);
        }
    });
})(jQuery);
